package dem1;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-04-16
 * Time: 9:00
 */

class MyLinkedList {

    LinkedNode head;
    LinkedNode last;
    int size;
    class LinkedNode{
        int val;
        LinkedNode next;
        LinkedNode prev;
        public LinkedNode(int data){
            val = data;
        }
        public LinkedNode(){
        }
    }

    public MyLinkedList() {

    }

    public int get(int index) {
        if(index < 0 || index >= size){
            return -1;
        }else{
            LinkedNode cur = head;
            while(index != 0){
                cur = cur.next;
                index--;
            }
            return cur.val;
        }
    }

    public void addAtHead(int val) {
        LinkedNode node = new LinkedNode(val);
        if(head == null){
            head = node;
            last = node;
        }else{
            head.prev = node;
            node.next = head;
            head = node;
        }
        size++;
    }

    public void addAtTail(int val) {
        LinkedNode node = new LinkedNode(val);
        if(head == null){
            head = node;
            last = node;
        }else{
            last.next = node;
            node.prev = last;
            last = node;
        }
        size++;
    }

    public void addAtIndex(int index, int val) {
        if(index > size){
            return;
        }
        if(index <= 0){
            addAtHead(val);
        }else if(index == size){
            addAtTail(val);
        }else{
            index = index - 1;
            LinkedNode cur = head;
            while(index != 0){
                cur = cur.next;
                index--;
            }
            LinkedNode node = new LinkedNode(val);
            node.next = cur.next;
            node.prev = cur;
            cur.next = node;
            cur.next.prev = node;
        }
        size++;
    }

    public void deleteAtIndex(int index) {
        if(index < 0 || index >= size){
            return;
        }else{
            LinkedNode cur = head;
            while(index != 0){
                cur = cur.next;
                index--;
            }
            if(cur == head){
                head = head.next;
                head.prev = null;
            }else if(cur == last){
                last = last.prev;
                last.next = null;
            }else{
                cur.prev = cur.next;
                cur.next.prev = cur.prev;
            }
        }
        size--;
    }
    ;
}

public class Test {
    public static void main(String[] args) {
        MyLinkedList myLinkedList = new MyLinkedList();
        myLinkedList.addAtHead(1);
        myLinkedList.addAtTail(3);
        myLinkedList.addAtIndex(1,2);
        myLinkedList.get(1);
        myLinkedList.deleteAtIndex(1);
        myLinkedList.get(1);
    }
}
